﻿using JWT;
using JWT.Algorithms;
using JWT.Serializers;
using System;
using System.Collections.Generic;

namespace DefeatEpidemic.Common
{
    public class JwtHelper
    {
        public static bool EncryptToken(Dictionary<string, object> dic, string secret, out string token)
        {
            try
            {
                IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
                IJsonSerializer serializer = new JsonNetSerializer();
                IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
                IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
                token = encoder.Encode(dic, secret);
            }
            catch (Exception ex)
            {
                token = "error_" + ex.Message;
                return false;
            }
            return true;
        }

        public static bool DecryptToken(string token, string secret, out string json_decode)
        {
            try
            {
                IJsonSerializer serializer = new JsonNetSerializer();
                IDateTimeProvider provider = new UtcDateTimeProvider();
                IJwtValidator validator = new JwtValidator(serializer, provider);
                IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
                IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder);
                json_decode = decoder.Decode(token, secret, verify: true);
            }
            catch (Exception ex)
            {
                json_decode = "error_" + ex.Message;
                return false;
            }
            return true;
        }
        /// <summary>
        /// 序列化jwt
        /// </summary>
        /// <param name="json"></param>
        /// <param name="jwt"></param>
        /// <returns></returns>
        public static bool DeserializeJsonToModel(string json, out JwtModel jwt)
        {
            try
            {
                jwt = JsonHelper.JsonDeserialize<JwtModel>(json);
            }
            catch (Exception)
            {
                jwt = null;
                return false;
            }
            return true;
        }

        /// <summary>
        /// 时间戳转时间
        /// </summary>
        /// <param name="timeStamp"></param>
        /// <returns></returns>
        public static DateTime ConvertStringToDateTime(string timeStamp)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(timeStamp + "0000");
            TimeSpan toNow = new TimeSpan(lTime);
            return dtStart.Add(toNow);
        }
        /// <summary>
        /// 时间转时间戳
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>

        public static long ConvertDateTimeToInt(System.DateTime time)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0));
            long t = (time.Ticks - startTime.Ticks) / 10000;   //除10000调整为13位      
            return t;
        }
    }


    /// <summary>
    /// jwt模型
    /// </summary>
    public class JwtModel
    {
        /// <summary>
        /// 主题
        /// </summary>
        public string sub { get; set; }
        /// <summary>
        /// JWT ID,JWT的唯一标识
        /// </summary>
        public string jti { get; set; }
        /// <summary>
        /// JWT颁发的时间
        /// </summary>
        public string iat { get; set; }
        /// <summary>
        /// 签发者
        /// </summary>
        public string issure { get; set; }
        /// <summary>
        /// jwt的接收该方，非必须 
        /// </summary>
        public string audience { get; set; }
        /// <summary>
        /// JWT生命周期
        /// </summary>
        public string exp { get; set; }
        /*注意：除以上属性外，也可增加自定义属性，且也上属性并非都为必填*/
    }
}
